import asyncio
from lib.net.index import wlan
from lib.sensors.inmp441.recorder import Inmp441

__service__ = "voice_tcp_audio"
__description__ = "upload i2s audio to tcp server"


def init():
    if not wlan.is_connected():
        print("wifi not connected")


index = 0

TCP_SERVER_IP = "106.53.186.158"
TCP_SERVER_PORT = 5000

async def run():
    global index
    mic = Inmp441(2, 1, 0)
    try:
        reader, writer = await asyncio.open_connection(TCP_SERVER_IP, TCP_SERVER_PORT)
        print("TCP 已连接服务器")
    except Exception as e:
        print("TCP 连接失败:", e)
        return

    while True:
        try:
            pcm_data = mic.record_bytes(1024)
            index += 1

            await writer.awrite(pcm_data)
            print(f"包{index}, 发送了 {len(pcm_data)} 字节")

            await asyncio.sleep_ms(20)
        except Exception as e:
            print("发送数据出错:", e)
            break


if __name__ == "__main__":
    if not wlan.is_connected():
        print("正在连接WiFi...")
        wlan.connect()

    if wlan.is_connected():
        try:
            asyncio.run(run())
        except KeyboardInterrupt:
            print("演示结束")
        except Exception as e:
            print(f"运行出错: {e}")
    else:
        print("WiFi未连接，无法运行程序")
